package com.orangelife.webservice.service.propFeePreBill.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.orangelife.exception.AppBizException;
import com.orangelife.service.feeDetail.IFeeDetailService;
import com.orangelife.service.offset.IOffsetService;
import com.orangelife.service.propFeeAmountLog.model.PropFeeAmountLogDto;
import com.orangelife.service.propFeePreBill.IPropFeePreBillService;
import com.orangelife.service.propFeePreBill.model.PropFeePreBillDto;
import com.orangelife.setting.constant.CodeConst;
import com.orangelife.setting.constant.InfoConst;
import com.orangelife.utils.PropertyUtils;
import com.orangelife.utils.StringUtils;
import com.orangelife.webservice.base.BaseService;
import com.orangelife.webservice.base.PageUtils;
import com.orangelife.webservice.service.propFeePreBill.IPropFeePreBillWebService;

/*****************************************************************
 * Copyright(C) ORANGELIFE Corporation 2015. All Rights Reserved.
 *****************************************************************/
/*
 * ============================================================== 功能名
 * propFeePreBill类 的WebService基本作业
 * 
 * @author zhr
 * 
 * @version 1.1.0
 * 
 * @date 2016-11-24 14:03:57
 * ==============================================================
 */
@Service("webservice_propFeePreBill")
public class PropFeePreBillWebServiceImpl extends BaseService implements
		IPropFeePreBillWebService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Resource(name = "propFeePreBillService")
	private IPropFeePreBillService propFeePreBillService;

	@Resource(name = "offsetService")
	private IOffsetService offsetService;
	@Resource(name = "feeDetailService")
	private IFeeDetailService feeDetailService;

	@Override
	public Response addPropFeePreBill(HttpServletRequest servletRequest,
			final PropFeePreBillDto propFeePreBill) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		propFeePreBill.setCreateuserID(pageUtils.getBaseSession().getUserID());
		propFeePreBill.setReceiverID(pageUtils.getBaseSession().getUserID());
		propFeePreBill.setReceiver(StringUtils.isBlank(pageUtils
				.getBaseSession().getTrueName()) ? pageUtils.getBaseSession()
				.getLoginName() : pageUtils.getBaseSession().getTrueName());
		propFeePreBill.setAccessToken(pageUtils.getBaseSession().getKey());

		if (StringUtils.isBlank(propFeePreBill.getFeeType())) {
			throw new AppBizException(2, "类型信息");
		}

		propFeePreBill.setType(propFeePreBill.getFeeType());
		if (propFeePreBill.getFeeType().equals("2")) {
			if (propFeePreBill.getFeedetailIDs() == null
					|| propFeePreBill.getFeedetailIDs().size() <= 0) {
				throw new AppBizException(2, "缴费信息");
			}

			Map<String, Object> propFeeDetail = new HashMap<String, Object>();
			propFeeDetail.put("feeDetailIDs", propFeePreBill.getFeedetailIDs());
			propFeeDetail.put("status", "0");
			List<Map<String, Object>> details = feeDetailService
					.findropFeeDetailByMap(propFeeDetail);
			if (details == null || details.size() == 0) {
				throw new AppBizException(2, "亲，缴费信息已经变动请重新选择");
			}
		}
		final String commID = propFeePreBill.getCommID();
		final String apartmentID = propFeePreBill.getApartmentID();
		final String userID = propFeePreBill.getReceiverID();
		final String userName = propFeePreBill.getReceiver();

		int result = propFeePreBillService
				.addPropFeePreBillInfo(propFeePreBill);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		try {
			if (propFeePreBill.getType().equals("1")) {
				Thread thread = new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							Thread.sleep(1000);
							offsetService.autoOffset(commID, apartmentID,
									userID, userName);
						} catch (Exception e) {
							logger.error(e.getMessage());
						}
					}
				});
				thread.start();
			}
			if (propFeePreBill.getType().equals("2")) {
				Thread thread = new Thread(new Runnable() {
					@Override
					public void run() {
						try {
							Thread.sleep(1000);
							offsetService.offsetByDetail(commID, apartmentID,
									userID, propFeePreBill.getFeedetailIDs(),
									userName, propFeePreBill.getPreBillID(),
									propFeePreBill.getMoney());
						} catch (Exception e) {
							logger.error(e.getMessage());
						}
					}
				});
				thread.start();
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		}

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "添加实体成功");

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("preBillID", propFeePreBill.getPreBillID());
		return this.normalResp(map);
	}

	@Override
	public Response editPropFeePreBill(HttpServletRequest servletRequest,
			PropFeePreBillDto propFeePreBill) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(propFeePreBill.getPreBillID(),
				"preBillID");
		if (error != null) {
			return error;
		}

		/************************************************
		 * 输入参数检查
		 ************************************************/
		// TODO;

		propFeePreBill.setEdituserID(pageUtils.getBaseSession().getUserID());
		int result = propFeePreBillService.editPropFeePreBill(propFeePreBill);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "修改实体成功");

		return this.normalResp();
	}

	@Override
	public Response deletePropFeePreBill(HttpServletRequest servletRequest,
			String preBillID) throws Exception {
		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(preBillID, "preBillID");
		if (error != null) {
			return error;
		}
		int result = propFeePreBillService
				.deletePropFeePreBillByLogic(preBillID);
		if (!(result > 0)) {
			return this.abnormalResp(CodeConst.BIS_CODE_13006,
					InfoConst.BIS_INFO_13006);
		}
		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "删除实体成功");

		return this.normalResp();
	}

	@Override
	public Response findPropFeePreBillByID(HttpServletRequest servletRequest,
			String preBillID) throws Exception {

		/************************************************
		 * 检查session
		 ************************************************/
		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		/************************************************
		 * 输入参数ID检查
		 ************************************************/
		Response error = this.validateUUId(preBillID, "preBillID");
		if (error != null) {
			return error;
		}
		PropFeePreBillDto propFeePreBill = propFeePreBillService
				.findPropFeePreBillByID(preBillID);

		Map<String, Object> maps = new HashMap<String, Object>();

		if (propFeePreBill != null) {

		}

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "查询实体成功");
		return this.normalResp(propFeePreBill);
	}

	@Override
	public Response getAllPropFeePreBill(HttpServletRequest servletRequest,
			String type, String commID, String searchType, String startTime,
			String endTime, String payTypes, String search, String status,
			String tsCreate, String pageIndex, String pageSize)
			throws Exception {

		PageUtils pageUtils = this.validatePageAndSetPage(servletRequest,
				pageIndex, pageSize);
		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/
		List<Map<String, Object>> list = propFeePreBillService
				.findPropFeePreBillByPage(type, commID, searchType, startTime,
						endTime, payTypes, tsCreate == null ? null : tsCreate,
						search == null ? null : search, status,
						pageUtils.getiPageIndex(), pageUtils.getiPageSize());

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginName() + new Date()
				+ "查询实体成功");

		return this.normalResp(pageUtils.getiPageIndex(),
				pageUtils.getiPageSize(), total,
				PropertyUtils.turnToEntity(list));
	}

	@Override
	public Response bauthFindPropFeePreBill(HttpServletRequest servletRequest,
			List<String> propFeePreBill) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeePreBill == null || propFeePreBill.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", propFeePreBillService
					.bauthfindPropFeePreBill(propFeePreBill));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response bauthFindPropFeePreBills(HttpServletRequest servletRequest,
			Map<String, Object> propFeePreBill) throws Exception {

		Map<String, Object> map = new HashMap<String, Object>();
		/************************************************
		 * 根据批量查询
		 ************************************************/
		try {

			/************************************************
			 * 输入参数ID检查
			 ************************************************/
			if (propFeePreBill == null || propFeePreBill.size() <= 0) {
				logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
				return this.abnormalResp(CodeConst.SYS_CODE_1001,
						InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			}

			map.put("pageEntity", PropertyUtils
					.turnToEntity(propFeePreBillService
							.bauthfindPropFeePreBillByMap(propFeePreBill)));
			map.put("errInfo", "ok");
			map.put("errCode", "0");
		} catch (AppBizException e) {
			map.put("errInfo", e.getMessage());
			map.put("errCode", e.getCode());
		}

		return Response.ok(map).build();

	}

	@Override
	public Response clearCache(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		propFeePreBillService.clearCache();
		return this.normalResp();
	}

	@Override
	public Response getTotalAmount(HttpServletRequest servletRequest,
			String type, String commID, String searchType, String startTime,
			String endTime, String payTypes, String search, String tsCreate)
			throws Exception {

		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}

		if (!StringUtils.isBlank(tsCreate)) {
			StringUtils.isTime(tsCreate);
			tsCreate = String.valueOf(Long.parseLong(tsCreate) / 1000);
		}
		/************************************************
		 * 查询列表
		 ************************************************/
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("totalAmount", 0.00);

		map = propFeePreBillService.getTotalAmount(type, commID, searchType,
				startTime, endTime, payTypes, tsCreate == null ? null
						: tsCreate, search == null ? null : search);

		logger.info(pageUtils.getBaseSession().getLoginName() + "在"
				+ pageUtils.getBaseSession().getLoginType() + "端" + new Date()
				+ "时" + "查询实体成功");
		return this.normalResp(map);
	}

	@Override
	public synchronized Response addPreBill(HttpServletRequest servletRequest,
			final PropFeePreBillDto propFeePreBill) throws Exception {
		PropFeePreBillDto p = propFeePreBillService
				.findPropFeePreBillByOrderID(propFeePreBill.getOrderID());
		if (p != null)
			return this.normalResp();
		else {
			if ("5".equals(propFeePreBill.getPayChannel())) {

				propFeePreBill
						.setPayType(PropFeeAmountLogDto.STATEMENT_TYPE_MP_WX);

			}
			if (StringUtils.isBlank(propFeePreBill.getFeeType())) {
				throw new AppBizException(2, "类型信息");
			}
			propFeePreBill.setType(propFeePreBill.getFeeType());
			if (propFeePreBill.getFeeType().equals("2")) {
				if (propFeePreBill.getFeedetailIDs() == null
						|| propFeePreBill.getFeedetailIDs().size() <= 0) {
					throw new AppBizException(2, "缴费信息");
				}

				Map<String, Object> propFeeDetail = new HashMap<String, Object>();
				propFeeDetail.put("feeDetailIDs",
						propFeePreBill.getFeedetailIDs());
				propFeeDetail.put("status", "0");
				List<Map<String, Object>> details = feeDetailService
						.findropFeeDetailByMap(propFeeDetail);
				if (details == null || details.size() == 0) {
					throw new AppBizException(2, "亲，缴费信息已经变动请重新选择");
				}
			}

			int result = propFeePreBillService
					.addPropFeePreBillInfo(propFeePreBill);
			if (!(result > 0)) {
				return this.abnormalResp(CodeConst.BIS_CODE_13006,
						InfoConst.BIS_INFO_13006);
			}

			final String commID = propFeePreBill.getCommID();
			final String apartmentID = propFeePreBill.getApartmentID();
			try {

				if (propFeePreBill.getType().equals("2")) {
					Thread thread = new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								Thread.sleep(1000);
								offsetService.offsetByDetail(commID,
										apartmentID, null,
										propFeePreBill.getFeedetailIDs(), null,
										propFeePreBill.getPreBillID(),
										propFeePreBill.getMoney());
							} catch (Exception e) {
								logger.error(e.getMessage());
							}
						}
					});
					thread.start();
				}
				if (propFeePreBill.getType().equals("1")) {

					Thread thread = new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								Thread.sleep(1000);
								offsetService.autoOffset(commID, apartmentID,
										null, null);
							} catch (Exception e) {
								logger.error(e.getMessage());
							}
						}
					});
					thread.start();
				}

			} catch (Exception e) {
				logger.error(e.getMessage());
			}

		}
		return this.normalResp();
	}

	@Override
	public Response cancelPropFeePreBill(HttpServletRequest servletRequest,
			PropFeePreBillDto propFeePreBill) throws Exception {

		PageUtils pageUtils = this.validateLogin(servletRequest);

		if (pageUtils.getResponse() != null) {
			return pageUtils.getResponse();
		}
		if (StringUtils.isBlank(propFeePreBill.getPreBillID())) {

			this.abnormalResp(98, "账单ID不能为空");
		}

		propFeePreBill.setCancelMan(pageUtils.getBaseSession().getRealname());
		propFeePreBill.setCancelTime(new Date());
		propFeePreBill.setCancelManID(pageUtils.getBaseSession().getUserID());
		propFeePreBillService.cancelPropFeePreBill(propFeePreBill);
		// TODO Auto-generated method stub
		return this.normalResp();
	}

	@Override
	public Response bauthfindInfos(HttpServletRequest servletRequest,
			Map<String, Object> propFeePreBill) throws Exception {

		if (propFeePreBill == null || propFeePreBill.size() <= 0) {
			logger.error(InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
			return this.abnormalResp(CodeConst.SYS_CODE_1001,
					InfoConst.SYS_INFO_1001, "亲，请输入相关的参数");
		}
		String pageIndex = propFeePreBill.get("pageIndex") + "";
		String pageSize = propFeePreBill.get("pageSize") + "";

		List<Map<String, Object>> list = propFeePreBillService
				.bauthfindPropFeePreBillByMap(propFeePreBill,
						Integer.parseInt(pageIndex), Integer.parseInt(pageSize));

		/************************************************
		 * 查询列表
		 ************************************************/

		/************************************************
		 * 返回结果设定
		 ************************************************/
		Long total = ((Page<Map<String, Object>>) list).getTotal();

		return this.normalResp(Integer.parseInt(pageIndex),
				Integer.parseInt(pageSize), total,
				PropertyUtils.turnToEntity(list));
	}
}
